<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="login-popup">
      <view class="popup-header">
        <text class="popup-title">商家登录</text>
        <view class="close-btn" @click="closePopup">×</view>
      </view>
      
      <view class="popup-content">
        <view class="login-tabs">
          <view 
            class="login-tab" 
            :class="{'active': loginType === 1}" 
            @click="loginType = 1"
          >
            密码登录
          </view>
          <view 
            class="login-tab" 
            :class="{'active': loginType === 2}" 
            @click="loginType = 2"
          >
            验证码登录
          </view>
        </view>
        
        <!-- 密码登录表单 -->
        <view v-if="loginType === 1" class="login-form">
          <view class="form-item">
            <input 
              class="input" 
              type="text" 
              v-model="loginForm.username" 
              placeholder="请输入商家账号/手机号" 
            />
          </view>
          <view class="form-item">
            <input 
              class="input" 
              type="password" 
              v-model="loginForm.password" 
              placeholder="请输入密码" 
            />
          </view>
          <view class="form-options">
            <label class="remember-pwd">
              <checkbox :checked="rememberPassword" @tap="rememberPassword = !rememberPassword" 
                style="transform:scale(0.7)" color="#FF8C42" />
              <text>记住密码</text>
            </label>
            <text class="forgot-pwd" @click="forgotPassword">忘记密码?</text>
          </view>
          <button 
            class="login-btn" 
            :disabled="isLoading"
            @click="handleLogin"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
        </view>
        
        <!-- 验证码登录表单 -->
        <view v-else class="login-form">
          <view class="form-item">
            <input 
              class="input" 
              type="text" 
              v-model="loginForm.phone" 
              placeholder="请输入手机号"
              maxlength="11"
            />
          </view>
          <view class="form-item verify-code">
            <input 
              class="input" 
              type="text" 
              v-model="loginForm.verifyCode" 
              placeholder="请输入验证码"
              maxlength="4"
            />
            <button 
              class="code-btn" 
              :disabled="cooldown > 0" 
              @click="getVerifyCode"
            >
              {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
            </button>
          </view>
          <button 
            class="login-btn" 
            :disabled="isLoading"
            @click="handleLogin"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
        </view>
        
        <view class="action-links">
          <view class="register-link" @click="goToRegister">
            <text>注册商家账号</text>
          </view>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '@/store/user';
import { BASE_URL } from '@/config/env';
// import uni from 'uni-app'; // Declare the uni variable

const emit = defineEmits(['login-success', 'register']);
const popup = ref(null);
const userStore = useUserStore();
const loginType = ref(1); // 1: 密码登录, 2: 验证码登录
const isLoading = ref(false);
const cooldown = ref(0);
const cooldownTimer = ref(null);
const rememberPassword = ref(false);

// 登录表单
const loginForm = reactive({
  username: '',
  phone: '',
  password: '',
  verifyCode: ''
});

// 打开弹窗
const open = () => {
  if (popup.value) {
    // 尝试从本地存储获取保存的账号密码
    const savedUsername = uni.getStorageSync('merchantUsername');
    const savedPassword = uni.getStorageSync('merchantPassword');
    
    if (savedUsername && savedPassword) {
      loginForm.username = savedUsername;
      loginForm.password = savedPassword;
      rememberPassword.value = true;
    }
    
    popup.value.open();
  }
};

// 关闭弹窗
const closePopup = () => {
  popup.value.close();
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (!rememberPassword.value) {
    loginForm.username = '';
    loginForm.password = '';
  }
  loginForm.phone = '';
  loginForm.verifyCode = '';
  isLoading.value = false;
};

// 获取验证码
const getVerifyCode = async () => {
  // 验证手机号
  if (!loginForm.phone || !/^1\d{10}$/.test(loginForm.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 模拟API调用
    uni.showLoading({ title: '发送中...' });
    
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 开始倒计时
    cooldown.value = 60;
    cooldownTimer.value = setInterval(() => {
      cooldown.value--;
      if (cooldown.value <= 0) {
        clearInterval(cooldownTimer.value);
      }
    }, 1000);
    
    uni.hideLoading();
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '获取验证码失败，请重试',
      icon: 'none'
    });
  }
};

// 处理登录
const handleLogin = async () => {
  // 表单验证
  if (loginType.value === 1) {
    // 密码登录验证
    if (!loginForm.username || loginForm.username.trim() === '') {
      uni.showToast({
        title: '请输入商家账号或手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!loginForm.password || loginForm.password.trim() === '') {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
  } else {
    // 验证码登录验证
    if (!loginForm.phone || !/^1\d{10}$/.test(loginForm.phone)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!loginForm.verifyCode || loginForm.verifyCode.trim() === '') {
      uni.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
  }
  
  // 执行登录
  try {
    isLoading.value = true;
    
    // Prepare login data based on login type
    const loginData = loginType.value === 1 
      ? { username: loginForm.username, password: loginForm.password }
      : { phone: loginForm.phone, verifyCode: loginForm.verifyCode };
    
    // Make API request to backend
    const response = await uni.request({
      url: BASE_URL + '/api/merchant/auth/login',
      method: 'POST',
      data: loginData,
      header: {
        'content-type': 'application/json'
      }
    });
    console.log('登录响应:', response);
    
    // Check if request was successful
    if (response.statusCode === 200 && response.data.code === 200) {
      const { data } = response.data;
      
      // 检查商家状态
      if (data.status !== undefined && data.status !== 1) {
        let statusMessage = '';
        switch(data.status) {
          case 0:
            statusMessage = '您的账号已被停用，请联系管理员';
            break;
          case 2:
            statusMessage = '您的账号正在审核中，请耐心等待';
            break;
          default:
            statusMessage = '您的账号状态异常，请联系管理员';
        }
        
        uni.showToast({
          title: statusMessage,
          icon: 'none',
          duration: 3000
        });
        return;
      }
      
      // If remember password is checked, save credentials
      if (rememberPassword.value && loginType.value === 1) {
        uni.setStorageSync('merchantUsername', loginForm.username);
        uni.setStorageSync('merchantPassword', loginForm.password);
      } else {
        uni.removeStorageSync('merchantUsername');
        uni.removeStorageSync('merchantPassword');
      }
      
      // Create merchant info object from API response
      const merchantInfo = {
        id: data.merchantId || data.id,
        username: data.username,
        name: data.name,
        shopName: data.name, // Using name as shopName
        avatar: data.avatarUrl,
        phone: data.phone,
        status: data.status,
        roles: data.roles
      };
      
      // Update user store with merchant info and token
      userStore.login('merchant', merchantInfo, data.token);
      
      // Close popup
      popup.value.close();
      
      // Show success message
      uni.showToast({
        title: response.data.comments || '登录成功',
        icon: 'success'
      });
      
      // Trigger login success event
      emit('login-success');
    } else {
      // Show error message from API or default message
      uni.showToast({
        title: response.data.msg || '登录失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('登录请求失败:', error);
    uni.showToast({
      title: '登录失败，请检查网络连接',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 忘记密码
const forgotPassword = () => {
  uni.showToast({
    title: '忘记密码功能开发中',
    icon: 'none'
  });
};

// 跳转到注册页面
const goToRegister = () => {
  // 关闭当前弹窗
  popup.value.close();
  // 触发注册事件，让父组件处理
  emit('register');
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (cooldownTimer.value) {
    clearInterval(cooldownTimer.value);
  }
});

// 暴露方法给父组件
defineExpose({
  open,
  close: closePopup
});
</script>

<style>
.login-popup {
  width: 700rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.popup-header {
  position: relative;
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  font-size: 40rpx;
  color: #999;
  line-height: 1;
}

.popup-content {
  padding: 40rpx;
}

.login-tabs {
  display: flex;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.login-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s;
}

.login-tab.active {
  color: #FF8C42;
  border-bottom: 2rpx solid #FF8C42;
  font-weight: bold;
}

.login-form {
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 20rpx;
  position: relative;
}

.input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 40rpx;
  padding: 0 30rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  background-color: #f9f9f9;
}

.verify-code {
  display: flex;
  align-items: center;
}

.verify-code .input {
  flex: 1;
}

.code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 24rpx;
  background-color: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 40rpx;
  margin-left: 20rpx;
}

.code-btn[disabled] {
  color: #999;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.remember-pwd {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #666;
}

.forgot-pwd {
  font-size: 24rpx;
  color: #FF8C42;
}

.login-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  margin-bottom: 20rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
}

.login-btn[disabled] {
  opacity: 0.6;
}

.action-links {
  display: flex;
  justify-content: center;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

.register-link {
  padding: 10rpx;
  color: #FF8C42;
}
</style>